{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6cab655c",
   "metadata": {},
   "source": [
    "# Creating a Product Recommendation Solution to help people with analysis paralysis"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81dcbaa2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import necessary libraries\n",
    "import os\n",
    "import litellm\n",
    "from dotenv import load_dotenv\n",
    "from duckduckgo_search import DDGS\n",
    "from agents import Agent, Runner, trace\n",
    "from datetime import datetime\n",
    "from agents.extensions.models.litellm_model import LitellmModel\n",
    "import ipywidgets as widgets\n",
    "from IPython.display import display, Markdown"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c401bea7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load environment variables\n",
    "load_dotenv(override=True)\n",
    "#litellm._turn_on_debug()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70fa4952",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test your API keys - add this as a new cell\n",
    "async def test_api_keys():\n",
    "    print(\"Testing API connections...\")\n",
    "    \n",
    "    try:\n",
    "        # Test OpenAI\n",
    "        test_openai = LitellmModel(model=\"gpt-4o-mini\", api_key=os.getenv(\"OPENAI_API_KEY\"))\n",
    "        print(\"✅ OpenAI API key working\")\n",
    "    except Exception as e:\n",
    "        print(f\"❌ OpenAI API issue: {e}\")\n",
    "    \n",
    "    try:\n",
    "        # Test Gemini\n",
    "        test_gemini = LitellmModel(model=\"gemini-pro\", api_key=os.getenv(\"GEMINI_API_KEY\"))\n",
    "        print(\"✅ Gemini API key working\")\n",
    "    except Exception as e:\n",
    "        print(f\"❌ Gemini API issue: {e}\")\n",
    "        \n",
    "    try:\n",
    "        # Test DeepSeek\n",
    "        test_deepseek = LitellmModel(model=\"deepseek/deepseek-chat\", api_key=os.getenv(\"DEEPSEEK_API_KEY\"))\n",
    "        print(\"✅ DeepSeek API key working\")\n",
    "    except Exception as e:\n",
    "        print(f\"❌ DeepSeek API issue: {e}\")\n",
    "\n",
    "await test_api_keys()\n",
    "\n",
    "# System Status Check\n",
    "def check_system_status():\n",
    "    print(\"🔍 System Status Check\")\n",
    "    print(\"=\" * 30)\n",
    "    \n",
    "    # Check APIs\n",
    "    apis_working = []\n",
    "    if os.getenv(\"OPENAI_API_KEY\"):\n",
    "        apis_working.append(\"OpenAI ✅\")\n",
    "    if os.getenv(\"GEMINI_API_KEY\"):\n",
    "        apis_working.append(\"Gemini ✅\")\n",
    "    if os.getenv(\"DEEPSEEK_API_KEY\"):\n",
    "        apis_working.append(\"DeepSeek ✅\")\n",
    "    \n",
    "    print(f\"APIs: {', '.join(apis_working)}\")\n",
    "    print(f\"Language: {session.user_preferences['language']}\")\n",
    "    print(f\"Session messages: {len(session.conversation_history)}\")\n",
    "    print(f\"Available tools: {len([electronics_smarttech_tool, lifestyle_wellness_tool, entertainment_tool, home_garden_pets_tool, fashion_lifestyle_tool, sports_auto_industry_tool])}\")\n",
    "    \n",
    "    if len(apis_working) > 0:\n",
    "        print(\"🟢 System ready\")\n",
    "    else:\n",
    "        print(\"🔴 System not ready - check API keys\")\n",
    "\n",
    "# Uncomment to check status\n",
    "    #check_system_status()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2effdba",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define language selection\n",
    "language_selector = widgets.Dropdown(\n",
    "    options=['English', 'Spanish', 'Portuguese', 'French', 'Italian', 'German', 'Dutch', 'Chinese'],\n",
    "    value='English',\n",
    "    description='Language:',\n",
    ")\n",
    "\n",
    "display(language_selector)\n",
    "\n",
    "# Simplified Session Manager - let the agent handle region naturally\n",
    "class SessionManager:\n",
    "    def __init__(self):\n",
    "        self.conversation_history = []\n",
    "        self.user_preferences = {\n",
    "            \"language\": \"English\",\n",
    "            \"region\": \"\",  # Agent will manage this\n",
    "            \"current_request\": \"\"\n",
    "        }\n",
    "    \n",
    "    def add_message(self, role, content):\n",
    "        self.conversation_history.append({\n",
    "            \"role\": role,\n",
    "            \"content\": content,\n",
    "            \"timestamp\": datetime.now()\n",
    "        })\n",
    "    \n",
    "    def get_context(self):\n",
    "        return self.conversation_history[-5:] if len(self.conversation_history) > 5 else self.conversation_history\n",
    "    \n",
    "    def get_context_string(self):\n",
    "        \"\"\"Get conversation context as a string for the agent\"\"\"\n",
    "        if not self.conversation_history:\n",
    "            return \"\"\n",
    "        \n",
    "        context = \"Previous conversation:\\n\"\n",
    "        for msg in self.get_context():\n",
    "            role = msg[\"role\"].title()\n",
    "            context += f\"{role}: {msg['content']}\\n\"\n",
    "             \n",
    "        return context\n",
    "\n",
    "# Initialize session\n",
    "session = SessionManager()\n",
    "\n",
    "# Connect language widget to session (keep this part)\n",
    "def on_language_change(change):\n",
    "    session.user_preferences[\"language\"] = change['new']\n",
    "    print(f\"Language changed to: {change['new']}\")\n",
    "\n",
    "language_selector.observe(on_language_change, names='value')\n",
    "selected_language = language_selector.value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58c1d1cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === REGION AGENT ===\n",
    "region_search_instructions = f\"\"\"\n",
    "You are a region-specific online shop research agent.\n",
    "\n",
    "Your goal is to help users discover the most relevant, trustworthy, and accessible online shops based on their geographical location or specified region. Your response should include both major global e-commerce platforms and regionally popular, well-known options when possible.\n",
    "\n",
    "Instructions:\n",
    "1. Prioritize well-reviewed and popular shops in the specified region.\n",
    "2. Ensure the online shops cater to the user's expected product categories.\n",
    "3. Consider delivery availability and language support in the region.\n",
    "4. Only access or recommend world-known, verified links of reputable websites such as Amazon, Mercado Livre, Coolblue, Decathlon, and other trusted platforms.\n",
    "5. When performing searches, prefer Google Shopping results but avoid entering or scraping unknown or suspicious websites to minimize risks of viruses or compromised content.\n",
    "6. If a website is not widely recognized or trusted, do NOT access or recommend it.\n",
    "7. Present your findings in a clear, well-structured list.\n",
    "\n",
    "Always respond in English\n",
    "\"\"\"\n",
    "\n",
    "region_search_agent = Agent(\n",
    "    name=\"Region Search Agent\",\n",
    "    instructions=region_search_instructions,\n",
    "    model=LitellmModel(model=\"deepseek/deepseek-chat\", api_key=os.getenv(\"DEEPSEEK_API_KEY\"))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a4b62b0",
   "metadata": {},
   "source": [
    "## Let's start defining our specialist agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c8ee9c08",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Shared Gemini configuration for all specialist agents\n",
    "gemini_model_config = LitellmModel(model=\"gemini-2.0-flash-exp\", api_key=os.getenv(\"GEMINI_API_KEY\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adf2bb9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Electronics & Smart Tech\n",
    "electronics_smarttech_instructions = f\"\"\"\n",
    "You are an Electronics and Smart Tech Specialist Agent.\n",
    "\n",
    "You guide users in choosing modern technology products, including:\n",
    "- Laptops, PCs, phones, tablets\n",
    "- Smart home devices (e.g., Alexa, Google Nest)\n",
    "- Audio & Video gear (e.g., soundbars)\n",
    "- Computer accessories\n",
    "- TVs, wearables, and home security\n",
    "\n",
    "You understand requirements such as HDMI ARC, Bluetooth, price limits, and system configurations.\n",
    "\n",
    "Tags include:\n",
    "- Smart speakers\n",
    "- Home theater\n",
    "- Budget tech\n",
    "- ARC compatible sound systems\n",
    "\n",
    "Always respond in English.\n",
    "\"\"\"\n",
    "\n",
    "electronics_smarttech_agent = Agent(\n",
    "    name=\"Electronics & Smart Tech Specialist\",\n",
    "    instructions=electronics_smarttech_instructions,\n",
    "    model=gemini_model_config\n",
    ")\n",
    "\n",
    "# Lifestyle & Wellness\n",
    "lifestyle_wellness_instructions = f\"\"\"\n",
    "You are a Lifestyle and Wellness Specialist Agent.\n",
    "\n",
    "You help users find high-quality products related to health, nutrition, wellness, food, and parenting. Your expertise includes categories like:\n",
    "- Health & Beauty\n",
    "- Dietary Supplements\n",
    "- Sports Nutrition (e.g., protein powder)\n",
    "- Baby & Children’s Products\n",
    "- Food and Beverages\n",
    "\n",
    "You understand Amazon-style product tags such as:\n",
    "- Diet & food\n",
    "- Protein supplements\n",
    "- Sports supplements\n",
    "- Vitamins\n",
    "- Skincare\n",
    "- Baby food\n",
    "- Snacks\n",
    "\n",
    "Ask clarifying questions if needed and make relevant, safe, and trusted recommendations.\n",
    "\n",
    "Always respond in English.\n",
    "\"\"\"\n",
    "\n",
    "lifestyle_wellness_agent = Agent(\n",
    "    name=\"Lifestyle & Wellness Specialist\",\n",
    "    instructions=lifestyle_wellness_instructions,\n",
    "    model=gemini_model_config\n",
    ")\n",
    "\n",
    "# Entertainment & Media\n",
    "entertainment_instructions = f\"\"\"\n",
    "You are an Entertainment and Media Specialist Agent.\n",
    "\n",
    "You help users explore content across books, games, music, and video. Your categories include:\n",
    "- Books (fiction, non-fiction, eBooks)\n",
    "- Video Games (consoles, PC, accessories)\n",
    "- Music (vinyl, CDs, digital)\n",
    "- Movies & TV (DVDs, streaming options)\n",
    "\n",
    "Recognize user interests and recommend products that are relevant and popular.\n",
    "\n",
    "Always respond in English.\n",
    "\"\"\"\n",
    "\n",
    "entertainment_agent = Agent(\n",
    "    name=\"Entertainment & Media Specialist\",\n",
    "    instructions=entertainment_instructions,\n",
    "    model=gemini_model_config\n",
    ")\n",
    "\n",
    "# Home, Garden & Pets\n",
    "home_garden_pets_instructions = f\"\"\"\n",
    "You are a Home, Garden & Pets Specialist Agent.\n",
    "\n",
    "You assist users in selecting products that enhance home comfort, outdoor living, and pet care. You specialize in:\n",
    "- Furniture & Lighting\n",
    "- Gardening tools & equipment\n",
    "- Pet supplies (food, toys, accessories)\n",
    "- Decor & DIY\n",
    "\n",
    "Amazon tags include:\n",
    "- Home improvement\n",
    "- Garden furniture\n",
    "- Pet grooming\n",
    "- Home organization\n",
    "\n",
    "Always respond in English.\n",
    "\"\"\"\n",
    "\n",
    "home_garden_pets_agent = Agent(\n",
    "    name=\"Home, Garden & Pets Specialist\",\n",
    "    instructions=home_garden_pets_instructions,\n",
    "    model=gemini_model_config\n",
    ")\n",
    "\n",
    "# Fashion & Lifestyle Accessories\n",
    "fashion_lifestyle_instructions = f\"\"\"\n",
    "You are a Fashion & Lifestyle Accessories Specialist Agent.\n",
    "\n",
    "You help users find clothing, shoes, jewelry, and stylish accessories tailored to their tastes, needs, and occasions. You cover:\n",
    "- Men’s and Women’s Fashion\n",
    "- Shoes, Bags, Watches\n",
    "- Jewelry and Accessories\n",
    "\n",
    "Use tags like:\n",
    "- Casual wear\n",
    "- Formal wear\n",
    "- Accessories\n",
    "- Seasonal collections\n",
    "\n",
    "Provide outfit ideas or coordinate suggestions when possible.\n",
    "\n",
    "Always respond in English.\n",
    "\"\"\"\n",
    "\n",
    "fashion_lifestyle_agent = Agent(\n",
    "    name=\"Fashion & Lifestyle Specialist\",\n",
    "    instructions=fashion_lifestyle_instructions,\n",
    "    model=gemini_model_config\n",
    ")\n",
    "\n",
    "# Sports, Automotive & Industry\n",
    "sports_auto_industry_instructions = f\"\"\"\n",
    "You are a Sports, Automotive & Industry Specialist Agent.\n",
    "\n",
    "You specialize in products related to:\n",
    "- Sports and Outdoor Gear\n",
    "- Car parts, tools, and accessories\n",
    "- Industrial and Scientific Equipment\n",
    "\n",
    "You help users find:\n",
    "- Fitness equipment\n",
    "- Auto electronics\n",
    "- Professional tools\n",
    "- Lab and industry gear\n",
    "\n",
    "Tags include:\n",
    "- Outdoor adventure\n",
    "- Automotive accessories\n",
    "- Power tools\n",
    "- Camping & fitness gear\n",
    "\n",
    "Always respond in English.\n",
    "\"\"\"\n",
    "\n",
    "sports_auto_industry_agent = Agent(\n",
    "    name=\"Sports, Automotive & Industry Specialist\",\n",
    "    instructions=sports_auto_industry_instructions,\n",
    "    model=gemini_model_config\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb3e9065",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert specialist agents to tools\n",
    "electronics_smarttech_tool = electronics_smarttech_agent.as_tool(\n",
    "    tool_name=\"electronics_smarttech_specialist\",\n",
    "    tool_description=\"Get electronics and smart tech product recommendations\"\n",
    ")\n",
    "\n",
    "lifestyle_wellness_tool = lifestyle_wellness_agent.as_tool(\n",
    "    tool_name=\"lifestyle_wellness_specialist\",\n",
    "    tool_description=\"Get lifestyle and wellness product recommendations\"\n",
    ")\n",
    "\n",
    "entertainment_tool = entertainment_agent.as_tool(\n",
    "    tool_name=\"entertainment_specialist\",\n",
    "    tool_description=\"Get entertainment product recommendations\"\n",
    ")\n",
    "\n",
    "home_garden_pets_tool = home_garden_pets_agent.as_tool(\n",
    "    tool_name=\"home_garden_pets_specialist\", \n",
    "    tool_description=\"Get home, garden, and pet product recommendations\"\n",
    ")\n",
    "\n",
    "fashion_lifestyle_tool = fashion_lifestyle_agent.as_tool(\n",
    "    tool_name=\"fashion_lifestyle_specialist\",\n",
    "    tool_description=\"Get fashion and lifestyle product recommendations\"\n",
    ")\n",
    "\n",
    "sports_auto_industry_tool = sports_auto_industry_agent.as_tool(\n",
    "    tool_name=\"sports_auto_industry_specialist\",\n",
    "    tool_description=\"Get sports, automotive, and industry product recommendations\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4b7ac87",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Optional: Add web search capability\n",
    "# First install: pip install duckduckgo-search\n",
    "\n",
    "def web_search_tool(query: str) -> str:\n",
    "    \"\"\"Search the web for current information\"\"\"\n",
    "    try:\n",
    "        print(f\"🔍 Web search activated: {query}\")\n",
    "        with DDGS() as ddgs:\n",
    "            results = list(ddgs.text(query, max_results=3))\n",
    "            formatted_results = []\n",
    "            for result in results:\n",
    "                formatted_results.append(f\"**{result['title']}**\\n{result['body']}\\nSource: {result['href']}\")\n",
    "            print(f\"✅ Found {len(results)} search results\")\n",
    "            return \"\\n\\n\".join(formatted_results)\n",
    "    except Exception as e:\n",
    "        print(f\"❌ Search error: {e}\")\n",
    "        return f\"Search error: {e}\"\n",
    "\n",
    "# Convert to tool for the agents framework\n",
    "def create_search_tool():\n",
    "    \"\"\"Create a search tool compatible with the agents framework\"\"\"\n",
    "    def search_function(input: str) -> str:\n",
    "        return web_search_tool(input)\n",
    "    \n",
    "    # Create a mock agent for the tool conversion\n",
    "    search_agent = Agent(\n",
    "        name=\"Web Search Agent\",\n",
    "        instructions=\"You search the web for current information and return relevant results.\",\n",
    "        model=LitellmModel(model=\"gpt-4o-mini\", api_key=os.getenv(\"OPENAI_API_KEY\"))\n",
    "    )\n",
    "    \n",
    "    # Override the agent's run method to use our search function\n",
    "    async def custom_run(self, user_input):\n",
    "        return web_search_tool(user_input)\n",
    "    \n",
    "    search_agent.run = custom_run.__get__(search_agent, Agent)\n",
    "    \n",
    "    return search_agent.as_tool(\n",
    "        tool_name=\"web_search\",\n",
    "        tool_description=\"Search the web for current product information, prices, and availability\"\n",
    "    )\n",
    "\n",
    "# Create the search tool\n",
    "web_search_tool_agent = create_search_tool()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "735e093b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_manager_instructions():\n",
    "    current_language = session.user_preferences[\"language\"]\n",
    "    context = session.get_context_string()\n",
    "    \n",
    "    instructions = f\"\"\"\n",
    "You are the Manager Agent responsible for interacting with the user and coordinating the work of specialist agents.\n",
    "\n",
    "{context}\n",
    "\n",
    "Workflow:\n",
    "1. From the conversation context, identify if you know the user's region/country. Look for mentions like:\n",
    "   - \"I'm in Netherlands\", \"I live in Germany\", \"I'm from the US\"\n",
    "   - \"Dutch\", \"German\", \"American\" (referring to nationality)\n",
    "   - Any country or region references\n",
    "   \n",
    "2. If you don't know their region yet, ask for it politely.\n",
    "\n",
    "3. Once you have both region and product requirements:\n",
    "   - FIRST use web_search to find current prices and availability\n",
    "   - THEN use the Electronics & Smart Tech Specialist to get recommendations\n",
    "   - Combine both sources for comprehensive recommendations\n",
    "\n",
    "4. Present specific product recommendations with:\n",
    "   - Product name and brand\n",
    "   - Key features matching their requirements  \n",
    "   - Current price range (from web search)\n",
    "   - Regional availability/where to buy\n",
    "   \n",
    "Key Intelligence:\n",
    "- Remember region information from earlier in the conversation\n",
    "- \"Dutch\" = Netherlands, \"German\" = Germany, \"American/US/USA\" = United States, etc.\n",
    "- Use your knowledge to provide region-appropriate recommendations\n",
    "\n",
    "Always respond in {current_language}.\n",
    "\"\"\"\n",
    "    \n",
    "    return instructions\n",
    "\n",
    "# Manager Agent Creation\n",
    "def get_manager_agent():\n",
    "    return Agent(\n",
    "        name=\"Manager Agent\",\n",
    "        instructions=create_manager_instructions(),\n",
    "        tools=[electronics_smarttech_tool, lifestyle_wellness_tool, entertainment_tool, \n",
    "               home_garden_pets_tool, fashion_lifestyle_tool, sports_auto_industry_tool,\n",
    "               web_search_tool_agent],  # Add search tool here\n",
    "        model=LitellmModel(model=\"gemini-2.5-flash\", api_key=os.getenv(\"GEMINI_API_KEY\"))\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5a91d6a",
   "metadata": {},
   "source": [
    "## Display Menu Options for User"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea3b782c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Smart translation function using LLM\n",
    "async def translate_text(text, target_language):\n",
    "   \"\"\"Use LLM to translate text to target language\"\"\"\n",
    "   if target_language.lower() == \"english\":\n",
    "       return text\n",
    "   \n",
    "   try:\n",
    "       translation_prompt = f\"\"\"\n",
    "       Translate this text to {target_language}, keeping the same structure and formatting:\n",
    "       \n",
    "       \"{text}\"\n",
    "       \n",
    "       Return only the translated text, nothing else.\n",
    "       \"\"\"\n",
    "       \n",
    "       response = await litellm.acompletion(\n",
    "           model=\"gpt-4o-mini\",\n",
    "           messages=[{\"role\": \"user\", \"content\": translation_prompt}],\n",
    "           api_key=os.getenv(\"OPENAI_API_KEY\"),\n",
    "           max_tokens=200\n",
    "       )\n",
    "       \n",
    "       return response.choices[0].message.content.strip()\n",
    "   except Exception as e:\n",
    "       print(f\"Translation error: {e}\")\n",
    "       return text  # Fallback to original text\n",
    "\n",
    "# Dynamic menu system\n",
    "async def display_menu():\n",
    "   \"\"\"Display menu in selected language\"\"\"\n",
    "   # Update session language from widget\n",
    "   session.user_preferences[\"language\"] = language_selector.value\n",
    "   target_language = session.user_preferences[\"language\"]\n",
    "   \n",
    "   # Base menu in English\n",
    "   base_title = \"Sound System Recommendation Agent\"\n",
    "   base_options = [\n",
    "       \"Choose an option:\",\n",
    "       \"1. Quick test with sample query\",\n",
    "       \"2. Test intelligent region handling\",\n",
    "       \"3. Debug test (fresh session)\",\n",
    "       \"4. Launch interactive chat interface\",\n",
    "       \"5. Debug instructions\"\n",
    "   ]\n",
    "   \n",
    "   # Translate if needed\n",
    "   if target_language.lower() != \"english\":\n",
    "       title = await translate_text(base_title, target_language)\n",
    "       options = []\n",
    "       for option in base_options:\n",
    "           translated_option = await translate_text(option, target_language)\n",
    "           options.append(translated_option)\n",
    "   else:\n",
    "       title = base_title\n",
    "       options = base_options\n",
    "   \n",
    "   # Display menu\n",
    "   print(title)\n",
    "   print(\"=\" * 40)\n",
    "   for option in options:\n",
    "       print(option)\n",
    "   print()\n",
    "\n",
    "# Quick test - run this cell for a simple test\n",
    "async def quick_test():\n",
    "    try:\n",
    "        session.user_preferences[\"language\"] = language_selector.value\n",
    "        \n",
    "        test_query = \"I'm looking for a sound system for my living room under $1000\"\n",
    "        print(f\"🧪 Testing: {test_query}\")\n",
    "        \n",
    "        manager_agent = get_manager_agent()\n",
    "        session.add_message(\"user\", test_query)\n",
    "        result = await Runner.run(manager_agent, test_query)\n",
    "        session.add_message(\"assistant\", result.final_output)\n",
    "        \n",
    "        print(\"✅ Test completed successfully\")\n",
    "        print(f\"📊 Session has {len(session.conversation_history)} messages\")\n",
    "        print(result.final_output)\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"❌ Test failed: {str(e)}\")\n",
    "        session.add_message(\"error\", str(e))\n",
    "\n",
    "# Add this new test function\n",
    "async def test_intelligent_region():\n",
    "   try:\n",
    "       session.user_preferences[\"language\"] = language_selector.value\n",
    "       \n",
    "       print(\"=== TESTING INTELLIGENT REGION HANDLING ===\")\n",
    "       \n",
    "       # Test 1: Mention region indirectly\n",
    "       test_1 = \"I'm Dutch and need a sound system under 500 euros\"\n",
    "       print(f\"\\n1. Testing: {test_1}\")\n",
    "       \n",
    "       manager_agent = get_manager_agent()\n",
    "       session.add_message(\"user\", test_1)\n",
    "       result = await Runner.run(manager_agent, test_1)\n",
    "       session.add_message(\"assistant\", result.final_output)\n",
    "       \n",
    "       print(\"Response:\", result.final_output)\n",
    "       \n",
    "       # Test 2: Follow up\n",
    "       test_2 = \"I need HDMI ARC and Bluetooth support\"\n",
    "       print(f\"\\n2. Testing: {test_2}\")\n",
    "       \n",
    "       manager_agent = get_manager_agent()  # Refresh with context\n",
    "       session.add_message(\"user\", test_2)\n",
    "       result = await Runner.run(manager_agent, test_2)\n",
    "       session.add_message(\"assistant\", result.final_output)\n",
    "       \n",
    "       print(\"Response:\", result.final_output)\n",
    "       \n",
    "       print(f\"\\n=== FINAL SESSION STATE ===\")\n",
    "       print(f\"Total messages: {len(session.conversation_history)}\")\n",
    "       print(f\"Language: {session.user_preferences['language']}\")\n",
    "       \n",
    "   except Exception as e:\n",
    "       print(f\"Error: {e}\")\n",
    "\n",
    "# Debug test function\n",
    "async def debug_test():\n",
    "   # Clear session and start fresh\n",
    "   global session\n",
    "   session = SessionManager()\n",
    "   print(\"Session cleared. Starting fresh...\")\n",
    "   \n",
    "   session.user_preferences[\"language\"] = language_selector.value\n",
    "   \n",
    "   # First message\n",
    "   test_1 = \"I'm in Berlin and need 5kg ankle weights under 50 euros\"\n",
    "   print(f\"Testing: {test_1}\")\n",
    "   \n",
    "   session.add_message(\"user\", test_1)\n",
    "   print(f\"Context after first message: {session.get_context_string()}\")\n",
    "   \n",
    "   manager_agent = get_manager_agent()\n",
    "   result = await Runner.run(manager_agent, test_1)\n",
    "   session.add_message(\"assistant\", result.final_output)\n",
    "   \n",
    "   print(\"Response:\", result.final_output)\n",
    "\n",
    "# DEBUG: Check what instructions are being generated\n",
    "def debug_instructions():\n",
    "   print(\"=== DEBUG MANAGER INSTRUCTIONS ===\")\n",
    "   print(\"Session context:\")\n",
    "   print(session.get_context_string())\n",
    "   print(\"\\nGenerated instructions:\")\n",
    "   print(create_manager_instructions())\n",
    "   print(\"=\" * 50)\n",
    "\n",
    "# Call this to display menu in selected language\n",
    "await display_menu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2613eba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "\n",
    "def chat_interface(message, history):\n",
    "    try:\n",
    "        # Update session language from current widget value\n",
    "        session.user_preferences[\"language\"] = language_selector.value\n",
    "        session.add_message(\"user\", message)\n",
    "        session.user_preferences[\"current_request\"] = message\n",
    "        \n",
    "        # Simple status log instead of verbose context\n",
    "        print(f\"💬 Processing: {message[:50]}...\" if len(message) > 50 else f\"💬 Processing: {message}\")\n",
    "        \n",
    "        # Create fresh manager agent with current context\n",
    "        manager_agent = get_manager_agent()\n",
    "        \n",
    "        # Get response from manager agent\n",
    "        import asyncio\n",
    "        \n",
    "        try:\n",
    "            loop = asyncio.get_event_loop()\n",
    "        except RuntimeError:\n",
    "            loop = asyncio.new_event_loop()\n",
    "            asyncio.set_event_loop(loop)\n",
    "            \n",
    "        result = loop.run_until_complete(Runner.run(manager_agent, message))\n",
    "        \n",
    "        # Update session with assistant response\n",
    "        session.add_message(\"assistant\", result.final_output)\n",
    "        \n",
    "        # Clean the response to avoid syntax errors\n",
    "        clean_response = str(result.final_output).strip()\n",
    "        \n",
    "        return clean_response\n",
    "        \n",
    "    except Exception as e:\n",
    "        error_msg = f\"I encountered an error: {str(e)}. Please try again.\"\n",
    "        session.add_message(\"error\", error_msg)\n",
    "        return error_msg\n",
    "\n",
    "async def launch_chat():\n",
    "    \"\"\"Launch chat interface with dynamic translation\"\"\"\n",
    "    # Update language\n",
    "    session.user_preferences[\"language\"] = language_selector.value\n",
    "    target_language = session.user_preferences[\"language\"]\n",
    "    \n",
    "    # Base text in English\n",
    "    base_title = \"Product Recommendation Assistant\"\n",
    "    base_description = f\"Ask me for product recommendations! I'll help you find the perfect products for your region. Current language: {target_language}\"\n",
    "    base_examples = [\n",
    "        \"I need a sound system under 500 euros\",\n",
    "        \"I'm in Netherlands and looking for Bluetooth speakers\",\n",
    "        \"Recommend a laptop for programming under $1000 in USA\",\n",
    "        \"I'm in Germany and need fitness equipment for home use\"\n",
    "    ]\n",
    "    \n",
    "    # Translate if needed\n",
    "    if target_language.lower() != \"english\":\n",
    "        title = await translate_text(base_title, target_language)\n",
    "        description = await translate_text(base_description, target_language)\n",
    "        examples = []\n",
    "        for example in base_examples:\n",
    "            translated_example = await translate_text(example, target_language)\n",
    "            examples.append(translated_example)\n",
    "    else:\n",
    "        title = base_title\n",
    "        description = base_description\n",
    "        examples = base_examples\n",
    "    \n",
    "    demo = gr.ChatInterface(\n",
    "        fn=chat_interface,\n",
    "        title=title,\n",
    "        description=description,\n",
    "        examples=examples\n",
    "    )\n",
    "    \n",
    "    print(f\"Launching chat interface in {target_language}...\")\n",
    "    print(f\"Session initialized with {len(session.conversation_history)} messages\")\n",
    "    demo.launch(share=True, debug=True)\n",
    "\n",
    "# Uncomment to launch\n",
    "await launch_chat()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
